﻿using System;
using System.IO;
using System.IO.Packaging;
using System.Xml;
using OpenLS.Core.Serialization;
using OpenLS.Spreadsheet.Drawing;
using OpenLS.Spreadsheet.Serialization;

namespace OpenLS.Spreadsheet.Formats.Biff.OfficeArt
{
    internal class AnchorWrapper : IOfficeXmlSerializable
    {
        public AnchorWrapper()
        {
            
        }

        public AnchorWrapper(Anchor item)
        {
            _item = item;
        }
        private Anchor _item;
        internal const string ContentType = "application/vnd.ms-OpenLS.DrsPicture+xml";
        public const string RelationshipName = @"http://schemas.microsoft.com/office/2006/relationships/pictureXml";

        public Anchor Item
        {
            get { return _item; }
        }

        #region IOfficeXmlSerializable Members

        public void ReadXml(ReadContext context)
        {
            using (ReadContext c = context.Read("anchor"))
            {
                switch (c.ReaderLocalName)
                {
                    case "twoCellAnchor":
                        _item = new TwoCellAnchor(null);
                        break;
                    case "oneCellAnchor":
                        _item = new OneCellAnchor((Worksheet) null);
                        break;
                    case "absoluteAnchor":
                        _item = new AbsoluteAnchor(null);
                        break;
                    default:
                        throw new NotSupportedException();
                }
                ((IOfficeXmlSerializable) Item).ReadXml(c);
            }
        }

        public void WriteXml(WriteContext context)
        {
            using (var c = context.Write("anchor"))
            {
                c.WriteElement(_item);
            }
        }

        #endregion

        public void ReadPart(PackagePart picturePart)
        {
            using (Stream stream = picturePart.GetStream())
            {
                using (XmlReader reader = new XmlTextReader(stream))
                {
                    var context = new ReadContext(reader, picturePart,
                                                  SpreadsheetConstants.SpreadsheetDrawingNamespaceUri);
                    ReadXml(context);
                }
            }
        }


    }
}